/******************************************************************************
 *
 *  socket_tcp_fork_server.c
 *
 *  Created on: 2012-3-11
 *      Author: Michael
 *       Email: zhongchao.ustc@gmail.com
 *
 *  Copyright (c) Michael Chao Zhong
 *
 *****************************************************************************/

#include <string.h>
#include <stdio.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>

int main(int argc, char *argv[])
{
	// Get Port option
	if (argc < 2)
	{
		fprintf(stderr, "ERROR, no port provided\n");
		exit(1);
	}
	int port_no = atoi(argv[1]);

	// Get socket
	int socket_fd = socket(AF_INET, SOCK_STREAM, 0);

	// Bind
	struct sockaddr_in server_addr;
	bzero((char *) &server_addr, sizeof(server_addr));
	server_addr.sin_family = AF_INET;
	server_addr.sin_addr.s_addr = INADDR_ANY;
	server_addr.sin_port = htons(port_no);
	bind(socket_fd, (struct sockaddr *) &server_addr, sizeof(server_addr));

	// Listen
	listen(socket_fd, 5);

	while(1)
	{
		// Accept
		struct sockaddr_in client_addr;
		int client_addr_length = sizeof(client_addr);
		int socket_to_client = accept(socket_fd,
				(struct sockaddr *) &client_addr, &client_addr_length);

		// Read
		char buffer[1024];
		bzero(buffer, sizeof(buffer));
		read(socket_to_client, buffer, sizeof(buffer) - 1);
		printf("Here is the message: %s\n", buffer);

		// Write
		const char *data = "I got your message.";
		write(socket_to_client, data, sizeof(data));

		// Close
		close(socket_to_client);
	}

	close(socket_fd);

	return 0;
}
